package com.letoken.platform.job.jobhandler.monitor;

import cn.hutool.core.collection.CollUtil;
//import com.letoken.platform.app.service.AppUserLoginLogService;
import com.letoken.platform.pub.constant.RedisKeyConstant;
import com.letoken.platform.pub.exception.ApiServiceException;
import com.letoken.platform.pub.res.ApiResponse;
import com.letoken.platform.repo.app.dao.AppUserLoginLogMapper;
import com.letoken.platform.repo.app.po.AppUserLoginLog;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * @author wyl
 * @Description app用户登录日志job
 * @date 2023/2/8 15:03
 * @Version 1.0
 */
@Component
@Log4j2
public class AppUserLoginLogJob {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AppUserLoginLogMapper appUserLoginLogMapper;


    @XxlJob("Async_AppUserLoginLog")
    @Transactional(rollbackFor = Exception.class)
    public void appUserLoginLog() {
        ListOperations<String, AppUserLoginLog> listOps = redisTemplate.opsForList();
        int count = 2000;
        List<AppUserLoginLog> leftPop;
        int length = 0;
        Long size = listOps.size(RedisKeyConstant.LETOKEN_APP_USER_LOGIN_LOG);
        if (size != null) {
            length = size.intValue();
        }
        leftPop = listOps.range(RedisKeyConstant.LETOKEN_APP_USER_LOGIN_LOG, -count, -1);
        int end = length - count - 1;
        if (length <= count){
            redisTemplate.delete(RedisKeyConstant.LETOKEN_APP_USER_LOGIN_LOG);
        }else {
            listOps.trim(RedisKeyConstant.LETOKEN_APP_USER_LOGIN_LOG, 0, end);
        }
        try {
            if (CollUtil.isNotEmpty(leftPop)){
                int i = appUserLoginLogMapper.insertBatchSomeColumn(leftPop);
                if (i < 1){
                    throw new ApiServiceException("插入数据为0");
                }
            }
        } catch (Exception e) {
            if (CollUtil.isNotEmpty(leftPop)) {
                listOps.leftPushAll(RedisKeyConstant.LETOKEN_APP_USER_LOGIN_LOG, leftPop);
            }
            throw new ApiServiceException(e.getMessage());
        }

    }
}
